package com.cqxyd.smartsite.controller.vs1;

import com.cqxyd.smartsite.pojo.CraneRecord;
import com.cqxyd.smartsite.pojo.EnvRecord;
import com.cqxyd.smartsite.service.ProgramInfoService;
import com.cqxyd.smartsite.service.UploadRecordService;
import com.cqxyd.smartsite.util.JSONResult;
import com.cqxyd.smartsite.util.PostHelper;
import com.cqxyd.smartsite.version.ApiVersion;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@ApiVersion(1)
@RequestMapping(value = "{version}/api/env")
@Api(value = "环境监测(扬尘监控)信息接口", tags = "环境监测(扬尘监控)信息接口")
public class EnvRuntimeController1 {
    private final Logger logger = LoggerFactory.getLogger(EnvRuntimeController1.class);
    @Autowired
    private PostHelper postHelper;
    @Autowired
    private UploadRecordService uploadRecordService;
    @Autowired
    private ProgramInfoService programInfoService;

    @PostMapping(value = "record")
    @ApiOperation(value = "上传环境监测信息", notes = "上传环境监测信息", produces = "application/json")
    @ApiImplicitParams
            ({
                    @ApiImplicitParam(name = "serialNo", value = "主机（黑匣子）编号", required = true, paramType = "query", dataType = "String"),
                    @ApiImplicitParam(name = "recordTime", value = "采集时间（yyyy-MM-dd HH:mm:ss）", required = true, paramType = "query", dataType = "String"),
                    @ApiImplicitParam(name = "temperature", value = "温度", required = true, paramType = "query", dataType = "double"),
                    @ApiImplicitParam(name = "humidity", value = "湿度", required = true, paramType = "query", dataType = "double"),
                    @ApiImplicitParam(name = "pm2p5", value = "pm2.5数据", required = true, paramType = "query", dataType = "double"),
                    @ApiImplicitParam(name = "pm10", value = "pm10数据", required = true, paramType = "query", dataType = "double"),
                    @ApiImplicitParam(name = "noise", value = "噪音", required = true, paramType = "query", dataType = "double"),
                    @ApiImplicitParam(name = "windSpeed", value = "风速", required = true, paramType = "query", dataType = "double"),
                    @ApiImplicitParam(name = "windDirection", value = "风向", required = true, paramType = "query", dataType = "double")
            })
    public JSONResult<String> postElevator(@PathVariable("version") String version, String serialNo, String recordTime,
                                           Double temperature, Double humidity, Double pm2p5, Double pm10, Double noise, Double windSpeed, Double windDirection) {
        try {
            List<String> keyAndSecret = programInfoService.getKeyAndSecret(serialNo);
            if (keyAndSecret == null) {
                return JSONResult.errorMsg("设备未注册，获取项目信息失败");
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            List<EnvRecord> list = new ArrayList<EnvRecord>();
            Date realRecordTime = sdf.parse(recordTime);

            EnvRecord record = new EnvRecord();
            record.setSerialNo(serialNo);
            record.setRecordTime(realRecordTime);
            record.setTemperature(temperature);
            record.setHumidity(humidity);
            record.setPm2p5(pm2p5);
            record.setPm10(pm10);
            record.setNoise(noise);
            record.setWindSpeed(windSpeed);
            record.setWindDirection(windDirection);

            int recordId = uploadRecordService.insertAndGetId(serialNo, realRecordTime, record.toString(), "环境监测信息");

            if (recordId == 0) {
                String errorInfo = "保存环境监测信息上传记录出错：" + record.toString();
                logger.error(errorInfo);
                return JSONResult.errorMsg(errorInfo);
            } else {
                record.setSourceId(String.valueOf(recordId));
            }

            list.add(record);
            return postHelper.postEnvRecord(keyAndSecret.get(0), keyAndSecret.get(1), list);
        } catch (ParseException e) {
            e.printStackTrace();
            return JSONResult.errorMsg("时间转换异常，请确认格式为：yyyy-MM-dd HH:mm:ss");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return JSONResult.errorMsg("上传环境监测信息失败:" + e.getMessage());

        }
    }

}
